package com.ruoyi.business.controller;

import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.business.domain.Beds;
import com.ruoyi.business.domain.Employee;
import com.ruoyi.business.domain.model.buildTree;
import com.ruoyi.business.service.IBedsPlusService;
import com.ruoyi.business.service.IEmployeePlusService;
import com.ruoyi.common.annotation.Translation;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.business.domain.vo.BedsVo;
import com.ruoyi.business.domain.bo.BedsBo;
import com.ruoyi.business.service.IBedsService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 床位
 *
 * @author ruoyi
 * @date 2023-06-25
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/beds")
public class BedsController extends BaseController {

    private final IBedsService iBedsService;

    private final IBedsPlusService bedsPlusService;
    private final IEmployeePlusService employeePlusService;
    private final ISysNoticeService sysNoticeService;
    /**
     * 查询床位列表
     */
    @GetMapping("/list")
    public TableDataInfo<BedsVo> list(BedsBo bo, PageQuery pageQuery) {
        return iBedsService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出床位列表
     */
    @Log(title = "床位", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(BedsBo bo, HttpServletResponse response) {
        List<BedsVo> list = iBedsService.queryList(bo);
        ExcelUtil.exportExcel(list, "床位", BedsVo.class, response);
    }

    /**
     * 获取床位详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<BedsVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iBedsService.queryById(id));
    }

    /**
     * 新增床位
     */
    @Log(title = "床位", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody BedsBo bo) {
        return toAjax(iBedsService.insertByBo(bo));
    }

    /**
     * 修改床位
     */
    @Log(title = "床位", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody BedsBo bo) {
        return toAjax(iBedsService.updateByBo(bo));
    }

    /**
     * 删除床位
     *
     * @param ids 主键串
     */
    @Log(title = "床位", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        //bedsPlusService.removeBatchByIds(Arrays.asList(ids));
        bedsPlusService.trueDelete(ids[0]);
        return toAjax( true);
    }

    /**
     * 退宿舍
     *
     * @param id 主键串
     */
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "退床", businessType = BusinessType.UPDATE)
    @PostMapping("/clearBed/{id}")
    public R<Void> clearBed(@PathVariable Long id) {
        Beds bed= bedsPlusService.getById(id);
        LambdaUpdateWrapper<Employee> update_Employee_sql = new LambdaUpdateWrapper<Employee>().set(Employee::getRoomNumber, null).set(Employee::getAllocated,null).eq(Employee::getId, bed.getEmployeeId());

            //清空之前的床位
            LambdaUpdateWrapper<Beds> update_bed_sql = new LambdaUpdateWrapper<Beds>().set(Beds::getEmployeeId, null).set(Beds::getStatus,"空位").set(Beds::getUpdateTime,new DateTime()).eq(Beds::getId, id);
            bedsPlusService.update(update_bed_sql);

            Employee employeeModel=employeePlusService.getById(bed.getEmployeeId());
            SysNotice notice=new SysNotice();
            String noticeTitle = String.format("%s 已被退出宿舍", employeeModel.getFullName());
            notice.setNoticeTitle(noticeTitle);
            notice.setNoticeType("退宿");
            notice.setStatus("0");
            notice.setDepartment(employeeModel.getDepartment());
            notice.setRoomNumber(bedsPlusService.getbedDetailByid(employeeModel.getRoomNumber()));
            sysNoticeService.insertNotice(notice);
            //先发通知再清空员工的床位id号，不然找不到床位的编号了
            employeePlusService.update(update_Employee_sql);

        return toAjax( true);
    }

}
